﻿using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace WeatherHistory.Api.Configuration;

/// <summary>
///     Класс для работы с конфигурацией приложения
/// </summary>
public static class AppConfiguration
{
    private static ILogger<WebApplication> _logger = null!;

    /* Default values */
    /// <summary> Строка подключения к базе данных </summary>
    public static string DatabaseConnectionString { get; private set; } = "host=localhost;port=2222;database=weather-history;username=sber;password=best";

    /// <summary> URL ahjyntylf </summary>
    public static string UiUrl { get; private set; } = "http://localhost:3000";
    
    /// <summary>
    ///     Заполнение переменных конфигурации данными из окружения
    /// </summary>
    /// <param name="app">Ссылка на инстанс приложения</param>
    public static void UpdateEnvironmentVariables(this WebApplication app)
    {
        if (app.Environment.IsDevelopment()) return;

        _logger = app.Services.GetRequiredService<ILogger<WebApplication>>();

        DatabaseConnectionString = TryUpdateVariable(DatabaseConnectionString, "DATABASE_CONNECTION_STRING");
        UiUrl = TryUpdateVariable(UiUrl, "UI_URL");
    }

    private static string TryUpdateVariable(string variable, string name)
    {
        var environmentValue = Environment.GetEnvironmentVariable(name);
        if (string.IsNullOrWhiteSpace(environmentValue)) _logger.LogWarning("Environment variable {Name} not set", name);
        return environmentValue ?? variable;
    }
}